import { defineStore } from 'pinia'

const useStore = defineStore('my', {
  state: () => ({
    originList: [
      {
        pid: 'w-001',
        ptime: '2022-01-10 22:00:00',
        paddr: '长沙 -- 北京',
        price: 1000,
      },
      {
        pid: 'w-002',
        ptime: '2022-01-10 08:00:00',
        paddr: '长沙 -- 广州',
        price: 800,
      },
      {
        pid: 'w-003',
        ptime: '2022-01-10 14:00:00',
        paddr: '长沙 -- 云南',
        price: 600,
      },
    ],
    list: [],
  }),
  getters: {
    getList() {
      return this.list
    },

    // 获取 缓存数据(先访问本地缓存数据， 再访问状态数据)
    getLocalList() {
      // 获取本地浏览器缓存数据
      const localListJSON = sessionStorage.getItem(this.$id)

      if (localListJSON) {
        let localLists = JSON.parse(localListJSON)
        console.log('getLocalList localLists=>', localLists)
        return localLists.list ? localLists.list : []
      } else return this.list

      // return this.list;
    },
  },
  actions: {
    searchAction({ price }) {
      console.log('执行 searchAction price=>', price, this.originList.filter((item) => item.price >= price))

      this.list = this.originList.filter((item) => item.price >= price)
    },

    initListAction() {
      this.list = [...this.originList]
    },
  },
  persistence: {
    enabled: true, // 启用状态持久化功能
    type: 'session', // 指定使用 sessionStorage 缓存
    state: ['list'], // 指定要持久化的状态属性名称
  },
})

export default useStore